import json

from rest_framework import serializers

from app_User import models
''''''
'''第一种序列化方法'''
class UserSerializer(serializers.Serializer):
    '''
    table User
    id   username  password  sex(choice 1,2,3)  moreInfo(ForigenKey)
    '''

    id = serializers.CharField()   # '''第一种:'''
    myid = serializers.CharField(source=id)  # '''变更输出名字, 需要加参数 source=字段名'''
    sex = serializers.CharField(source='get_sex_display') # '''choice 如果想输出元祖右边的内容"男生"  CHOSE_SEX = ((0, '女生'), (1, '男生'))'''
    mf = serializers.CharField(source='student_detail.xxx.xxx属性名')    # '''ForeignKey'''

    #many to many 不能细调用,需要创建自定义函数
    rtf = serializers.SerializerMethodField() # many to many 序列方法 第一步
    def get_rtf(self,row):    # get_字段名   # many to many 序列方法 第二步
        row_obj_list = row.roles.all()
        rtf = []
        for item in row_obj_list:
            rtf.append({'id' : item.id, '字段名':item.字段名})
        return rtf

'''第二种序列化方法'''
class UserSerializer(serializers.ModelSerializer):
    '''
    table User
    id   username  password  sex(choice 1,2,3)  moreInfo(ForigenKey)
    '''
    oooo自定义字段 = serializers.CharField(source='get_xxx_display')
    rtf = serializers.SerializerMethodField()  # many to many 序列方法 第一步
    class Meta:
        model = models.Students
        # fields = '__all__'
        fields = ['id','username','内置字段名','oooo','rls(manytomany方法,2步)','group(如果想显示foreignkey的内容,添加extra_kwards)']
        extra_kwargs = {'group':{'source':'group.title(xxx属性名)'},}



    def get_rtf(self, row):  # get_字段名    # many to many 序列方法 第二步
        row_obj_list = row.roles.all()
        rtf = []
        for item in row_obj_list:
            rtf.append({'id': item.id, '字段名': item.字段名})
        return rtf


'''第三种最简单,通过meta depth=0来自动序列化,自动序列化连表'''
class UserSerializer(serializers.ModelSerializer):
    ''' id   username  password  sex(choice 1,2,3)  moreInfo(ForigenKey)'''

    class Meta:
        model = models.Students
        # fields = '__all__'
        fields = ['id','username','内置字段名','oooo','rls(manytomany方法,2步)','group(如果想显示foreignkey的内容,添加extra_kwards)']
        depth = 1



'''调用函数类'''
class viewclass(VIPview):
    std = models.Students.objects.all()
    std_ser = serializers.Serializer(instance=UserSerializer,many= True) #单一对象的话用many = Flase
    std_json = json.dumps(std_ser.data,ensure_ascii=False)  #ensure_ascii=False 不编码汉字
    return HttpResponse(std_json)